# 业务需求分析:

# 买票之前先要查票,必须经历的流程: 你在查票的同时,100个人也在查本此列票.
# 买票时,你要先从服务端获取到票数,票数>0 ,买票,然后服务端票数减一. 中间肯定有网络延迟.
from multiprocessing import Process
from multiprocessing import Lock
import time
import json
import os
import random
# 多进程原则上是不能互相通信的,它们在内存级别数据隔离的.不代表磁盘上数据隔离.
# 它们可以共同操作一个文件.

def search():
    time.sleep(random.random())
    with open('db.json',encoding='utf-8') as f1:
        dic = json.load(f1)
    print(f'剩余票数{dic["count"]}')


def get():
    with open('db.json',encoding='utf-8') as f1:
        dic = json.load(f1)
    time.sleep(random.randint(1,3))
    if dic['count'] > 0:
        dic['count'] -= 1
        with open('db.json', encoding='utf-8', mode='w') as f1:
            json.dump(dic,f1)
        print(f'{os.getpid()}用户购买成功')
    else:
        print('没票了.....')

def task(lock):
    search()
    lock.acquire()
    get()
    lock.release()


if __name__ == '__main__':
    lock = Lock()
    for i in range(5):
        p = Process(target=task,args=(lock,))
        p.start()


    # with open('db.json', encoding='utf-8',mode='w') as f1:
    #     json.dump({'count': 3},f1)
